'''
Created on Dec 6, 2009

@author: tliu
'''

import cgi
from util import AuthorizedPage
from error.TagError import TagError as TagError
from model.User import getUserByUsername
from google.appengine.ext.webapp import template
from model.Tagging import createTagging
from error.UserError import UserError as UserError
import os

class AddTagsPage(AuthorizedPage):
    
    def getIfAuthorized(self):
        error = self.request.get("error")
        target_user = self.request.get("user")
        try:
            target_user = getUserByUsername(target_user)
        except UserError:
            self.redirect('/error')
            return
        messages = {"bad_tag" : "A bad tag was chosen!",
                    "no_tag" : "No such tag exists!"}
        templatePath = os.path.join(os.path.dirname(__file__), 'add_tags.html')
        if not error in messages.keys():
            message = ""
        else:
            message = messages[error]
            
        tag_list = []
        for tag in self.authorizedUser.tag_list:
            tag_list.append({"name" : tag})   
            
        for tagging in self.authorizedUser.getTaggings():
            if tagging.tagged_user.username == target_user.username:
                for tag in tagging.tags:
                    for t in tag_list:
                        if t["name"] == tag:
                            t["checked"] = True
            
        self.outputHeader()
        self.response.out.write(template.render(templatePath, {"error" : message, 
                                                               "tag_list" : tag_list, 
                                                               "target_user" : target_user.name, 
                                                               "target_username" : target_user.username})) 
        
    def postIfAuthorized(self):
        try:
            tags = self.request.get_all("tags")
            tags = map(lambda tag:cgi.escape(tag), tags)
            target_user = self.request.get("target_username")
            target_user = getUserByUsername(target_user)
            for tag in tags:
                if tag not in self.authorizedUser.tag_list:
                    raise TagError("Bad Tag.")
            for tagging in self.authorizedUser.getTaggings():
                if tagging.tagged_user.username == target_user.username:
                    self.authorizedUser.taggings.remove(tagging.key())
                    tagging.delete()
            self.authorizedUser.addTagging(target_user, tags)
        except TagError:
            self.redirect('/add_tags?error=bad_tag&user='+target_user.username)
            return
        except UserError:
            self.redirect('/network?error=bad_user')
            return
 
        self.redirect('/network')
        return
